<template>
  <div class="acBox">
    <van-image fit="scale-down" :src="calendarInfo.default_img" />
    <div class="calendarInfo">
      <div class="acName pd10">{{ calendarInfo.title }}</div>
      <div class="acTime  pd10">
        活动时间：{{ calendarInfo.is_always_show }}
      </div>
      <div class="acTime  pd10">
        报名人数：
        <span>{{ calendarInfo.signup_maxnum }}</span>
      </div>
      <div class="acTime  bottom">活动地点：{{ calendarInfo.place }}</div>
      <div
        :class="['content', showMoreText ? 'heightAuto' : 'more']"
        v-html="calendarInfo.content"
      ></div>
      <div
        class="showMore"
        @click="showMoreText = !showMoreText"
        v-if="strlen(calendarInfo.content) > 125"
      >
        <div class="show">{{ showMoreText ? "收起详情" : "展开详情" }}</div>
        <van-icon
          name="dbarrow-down"
          :class="{ turn: showMoreText }"
          class-prefix="icon"
        />
      </div>
    </div>
    <!-- 长期活动日历选择 -->
    <calendar
      @chooseDisabled="clickDis"
      @chooseTimePeriod="chooseTimeP"
      @tdSelectId="tdSelectId"
      async-choose
      :calendarInfo="calendarInfo"
      @priceTotal="totalPrice(arguments)"
      v-if="calendarInfo.yy_date.length || calendarInfo.list.length"
    />

    <div
      :class="['preferential', myCoupon[cindex].usecoupon ? 'active' : '']"
      v-if="couponshow && myCoupon.length"
      @click="showList = true"
    >
      <div
        class="item van-row--flex"
        :style="{ color: myCoupon[cindex].usecoupon ? '#F17F2A' : '#DFDFDF' }"
      >
        <span
          >{{ myCoupon[cindex].coupon_name }} ￥{{
            myCoupon[cindex].cprice
          }}</span
        >
      </div>
      <van-icon
        class-prefix="icon"
        size="27px"
        name="sangedian"
        :color="myCoupon[cindex].usecoupon ? '#F17F2A' : '#DFDFDF'"
      />
    </div>
    <div class="preferential" v-if="couponshow && myCoupon.length == 0">
      <div class="item van-row--flex"><span>暂无可用优惠券</span></div>
    </div>
    <div class="preferential" v-if="cindex == -1">
      <div class="item van-row--flex">
        <van-icon name="checked" color="#DFDFDF" size="16px" />
        <span>不使用优惠券</span>
      </div>
    </div>
    <van-cell-group>
      <van-field
        label="姓   名"
        placeholder="请输入姓名"
        v-model="toi_username"
        required
      />
      <van-field
        label="手机号码"
        placeholder="请输入手机号"
        v-model="contact_phone"
        type="tel"
        required
      />
      <van-field
        label="身份证号"
        placeholder="请输入身份证号"
        v-model="id_card"
        type="tel"
      />
      <van-field
        class="remarks"
        placeholder="请在此输入内容,最多100字..."
        v-model="remarks"
        type="textarea"
        maxlength="100"
        autosize
        show-word-limit
      >
        <div slot="label" class="remarks_label">
          备注
          <span>(选填)</span>
        </div>
      </van-field>
    </van-cell-group>
    <div class="notice ">
      <div class="header">参观须知</div>
      <div class="noticeContent" v-html="calendarInfo.entrance"></div>
    </div>
    <div class="total">
      <p>
        合计金额：
        <span class="money">¥ {{ total }}</span>
        <span class="num">（{{ totalNum }}张）</span>
      </p>
      <div class="btn" @click="nextStep">提 交</div>
    </div>
    <van-popup v-model="showList" round position="bottom" style="height: 60%; ">
      <div class="myCouponList">
        <div class="top">
          <navTitle title="更多优惠券" :normal="false"></navTitle>
        </div>
        <div class="clist">
          <div
            class="citem"
            v-for="(item, index) in myCoupon"
            :key="index"
            @click="usecouponFn(index)"
          >
            <div class="pricebox">
              <div>
                <span class="priceUnit">￥</span>
                <span class="price">{{ item.cprice }}</span>
              </div>
              <div class="priceDes">{{ item.range_name }}</div>
            </div>
            <div class="iteminfo">
              <div class="itemname">{{ item.coupon_name }}</div>
              <div class="date">
                <span>
                  有效期：
                  <span v-if="item.date">{{ item.date }}</span>
                  <span v-else>永久有效</span>
                </span>
                <span
                  ><i
                    :class="[
                      'icon icon-xuanzhong',
                      item.usecoupon ? 'active' : '',
                    ]"
                  ></i
                ></span>
              </div>
              <div class="nowdate">
                <span v-if="item.date">还剩 {{ item.days }} 天过期</span>
              </div>
            </div>
          </div>
        </div>
        <div class="nouser">
          <van-button
            type="danger"
            block
            round
            text="不使用优惠券"
            @click="nousefn"
          ></van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {
  ActiveDetail,
  ActiveShortDetail,
  CouponMyCoupon,
  ActiveOrder,
} from "@/http/active";
import calendar from "@/components/calendar";
import navTitle from "@/components/navTitle";

// import {Session} from '@/assets/js/utils.js';
import { checkPhone, checkIdcard } from "../../assets/js/assist";
import { Dialog } from "vant";

export default {
  name: "acDetail",
  data() {
    return {
      showMoreText: false,
      calendarInfo: {
        yy_date: [],
        list: [],
        content: "",
      },
      total: 0,
      totalNum: 0,

      myCoupon: [],
      disabledCoupons: [],
      couponshow: false,
      cindex: 0,
      showList: false,
      tdid: "", //选中日期标识
      price_collect: [], //选择后的数组
      // 提交数据
      active_time_id: "",
      active_id: "",
      people_num: [],
      price_id: [],
      contact_phone: "",
      toi_username: "",
      id_card: "",
      remarks: "",
      id: "",
      work: "",
      idindex: "",
      api_token: null,
      is_always: 0,
    };
  },
  components: {
    calendar,
    navTitle,
  },
  created() {
    this.active_id = this.$route.query.active_id;
    this.is_always = this.$route.query.is_always;
    if (!this.active_id) {
      return this.$router.back();
    }
    if (this.$route.query.api_token) {
      localStorage.setItem("api_token", this.$route.query.api_token);
      this.api_token = this.$route.query.api_token;
      this.active_id && this._ActiveDetail();
    } else if (localStorage.getItem("api_token")) {
      this.active_id && this._ActiveDetail();
      this._CouponMyCoupon();
    }
  },
  watch: {
    total: function(e) {
      let that = this;
      if (e == 0 || e == "0.00") {
        console.log(e);
        that.nousefn();
      } else {
        that._CouponMyCoupon();
      }
    },
  },
  methods: {
    // 获取活动详情
    _ActiveDetail() {
      if (this.is_always == 1) {
        //长期活动
        ActiveDetail(this.active_id, this.api_token).then((res) => {
          if (res.status == 1) {
            this.calendarInfo = res.data;
            this.calendarInfo.list = []; //填充短期数据
          }
        });
      } else {
        //短期活动
        ActiveShortDetail(this.active_id, this.api_token).then((res) => {
          if (res.status == 1) {
            this.calendarInfo = res.data;
            this.calendarInfo.yy_date = []; //填充长期数据
          }
        });
      }
    },
    // 获取我的可用优惠券
    _CouponMyCoupon() {
      CouponMyCoupon(1, 0).then((res) => {
        this.couponshow = true;
        if (res.status == 1) {
          let myCoupon = res.data;
          myCoupon.map((item) => {
            item.usecoupon = false;
            item.date =
              item.date.split("-")[1] +
              "." +
              item.date.split("-")[2] +
              " ~ " +
              item.date.split("-")[4] +
              "." +
              item.date.split("-")[5];
          });
          this.myCoupon = myCoupon;
          if (myCoupon.length) {
            this.myCoupon[0].usecoupon = true;
          }
        }
        if (this.total == 0 || this.total == "0.00") {
          this.nousefn();
        }
      });
    },
    // 计算富文本真实字段数
    strlen(str) {
      var len = 0;
      if (!str) {
        return 0;
      }
      if (str.indexOf("<img") > 0) {
        return 130;
      }
      for (var i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
          // len++;
          // 非中文不加1
        } else {
          len += 2;
        }
      }
      return len;
    },
    // 使用我的优惠券
    usecouponFn(index) {
      this.myCoupon.map((item) => {
        item.usecoupon = false;
      });
      this.cindex = index;
      this.myCoupon[index].usecoupon = true;
      this.showList = false;
      this.total =
        this.myCoupon[index].cprice < this.total
          ? this.total - this.myCoupon[index].cprice
          : 0;
    },
    // 不使用优惠券
    nousefn() {
      console.log(this.myCoupon);
      this.myCoupon.map((item) => {
        console.log(item);
        item.usecoupon = false;
      });
      this.showList = false;
      // this.cindex = -1;
    },
    // 提交
    nextStep() {
      var {
        is_always,
        active_id,
        active_time_id,
        people_num,
        price_id,
        contact_phone,
        toi_username,
        id,
        work,
        tdid,
        price_collect,
        myCoupon,
        id_card,
        remarks,
      } = this;
      var idindex = myCoupon.findIndex((f) => {
        return f.usecoupon;
      });
      this.idindex = idindex;
      console.log(idindex);
      if (tdid == "" && is_always == 1) {
        return this.$toast("请选择日期");
      }
      if (active_time_id == "") {
        return this.$toast(
          `${is_always == 1 ? "请选择时段" : "请选择日期场次"}`
        );
      }
      if (price_collect.length == 0 && is_always == 1) {
        return this.$toast("请选择活动票");
      }
      if (toi_username == "") {
        return this.$toast("请输入姓名");
      }
      if (!checkPhone(contact_phone)) {
        return this.$toast("请输入正确的手机号");
      }
      if (id_card && !checkIdcard(id_card).status) {
        return this.$toast("请输入正确的身份证号");
      }
      let a = price_collect.filter((item) => {
        return item.value > 0;
      });
      a.map((i) => {
        people_num.push(i.value);
        price_id.push(i.price_id);
      });
      Dialog.confirm({
        title: "确认订单信息",
        message: "请确认订单信息",
      })
        .then(() => {
          ActiveOrder(
            active_id,
            active_time_id,
            people_num,
            price_id,
            contact_phone,
            toi_username,
            id_card,
            remarks,
            idindex > -1 ? myCoupon[idindex].id : "",
            work
          ).then((res) => {
            console.log(res);
            if (res.status == 1) {
              if (res.data.order_status == 1) {
                this.$router.replace({
                  path: "/active/success",
                  query: {
                    titem_id: res.data.titem_id,
                  },
                });
              } else if (res.data.order_status == 2) {
                this.$router.replace({
                  path: "/active/orderdetail",
                  query: {
                    titem_id: res.data.titem_id,
                  },
                });
              } else {
                // 报名出错时也需要置空数组
                a = [];
                this.people_num = [];
                this.price_id = [];
                this.$toast(res.data.order_status_name || "稍后再试！");
              }
            } else {
              a = [];
              this.people_num = [];
              this.price_id = [];
              this.$toast(res.msg || "当前活动不可约");
            }
          });
        })
        .catch(() => {
          // on cancel
          // 取消时，置空数组
          a = [];
          this.people_num = [];
          this.price_id = [];
        });

      console.log(this.people_num, this.price_id);
    },
    // 日期选中
    tdSelectId(e) {
      this.tdid = e;
    },
    // 不可选
    clickDis() {
      this.$toast("不可选");
    },
    /**
     * @日期重选判断（重选时需重新添加参观者）
     */
    chooseTimeP(e) {
      let _this = this;
      if (!e) {
        _this.active_time_id = "";
        return;
      }
      let { instance, item } = e;
      if (instance) instance.selectTimeActive(item);
      _this.active_time_id = item.active_time_id;
    },
    totalPrice(e) {
      this.total = e[0];
      this.totalNum = e[1];
      this.price_collect = e[2];
    },
  },
};
</script>

<style scoped lang="scss">
.acBox {
  min-height: 100vh;
  background-color: #eeeeee;
  position: relative;
  z-index: 1;
  padding-bottom: 200px;

  .calendarInfo {
    position: relative;
    z-index: 2;
    background-color: #fff;
    margin: -30px 0 0 0;
    border-radius: 24px;
    padding: 30px 20px;

    .pd10 {
      padding: 10px;
    }

    .acName {
      font-size: 34px;
      line-height: 48px;
    }

    .acTime {
      color: $fzColor;
      font-size: 28px;

      span {
        color: #757575;
      }

      &.bottom {
        border-bottom: 1px solid $bordercolor;
        padding: 10px 10px 30px 10px;
      }
    }

    .content {
      font-size: 30px;
      overflow: hidden;
      padding: 0 10px;
      margin: 30px 0;
      transition: height 0.3s ease-in-out;
      line-height: 44.4px;
      will-change: height;
      white-space: pre-wrap;

      &.more {
        @include ellipsis(5, 222px);
      }

      &.heightAuto {
        height: auto;
      }
    }

    .showMore {
      text-align: center;
      color: $baseColor;
      font-size: 28px;
      transition: ease-in-out 0.3s;

      /*background: linear-gradient(transparent, #fff);*/
      .show {
        margin-bottom: 10px;
        transition: ease-in-out 0.3s;
      }

      /deep/ .icon {
        transition: ease-in-out 0.5s;
        display: inline-block;

        &.turn {
          transform: rotate(180deg);
        }
      }
    }
  }

  .preferential {
    border-radius: 24px;
    margin-top: 20px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 25px 48px;
    font-size: 30px;
    color: #dfdfdf;

    .item {
      .van-icon {
        margin-right: 15px;
      }

      &.active {
        color: $fzColor;
      }
    }

    &.active {
      color: $fzColor;
    }
  }

  /deep/ .van-cell-group {
    border-radius: 24px;
    margin-top: 20px;
    overflow: hidden;
    padding: 0 40px;
  }

  .notice {
    padding: 0 30px;

    .header {
      padding: 30px 0;
      font-size: 30px;
      color: $fzColor;
      font-weight: bold;
    }

    .noticeContent {
      color: $fzColor;
      line-height: 48px;
      font-size: 28px;

      /deep/ * {
        background: transparent !important;
      }

      /deep/ img {
        max-width: 100%;
      }

      /deep/ video {
        max-width: 100%;
      }
    }
  }

  .total {
    width: 100%;
    height: 170px;
    background: #ffffff;
    position: fixed;
    bottom: 0;
    border-radius: 24px 24px 0px 0px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30px;
    z-index: 999;
    box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.1);

    p {
      font-size: 32px;
      font-weight: 500;
      color: rgba(50, 50, 50, 1);
      max-width: 420px;
      word-break: break-all;

      .money {
        color: #e10028;
      }

      .num {
        color: #646464;
      }
    }

    .btn {
      width: 240px;
      height: 72px;
      border-radius: 36px;
      background: #f17f2a;
      color: #ffffff;
      line-height: 72px;
      text-align: center;
      font-size: 32px;

      &:active {
        background: #ed9f65;
      }
    }
  }

  .myCouponList {
    height: 100%;
    position: relative;
    padding: 0 30px;

    .top {
      position: absolute;
      top: 0;
      background-color: #fff;
      left: 30px;
      right: 30px;
      padding: 50px 0;
      z-index: 10;
    }

    .clist {
      height: 100%;
      overflow: scroll;
      padding: 110px 0;
      position: relative;

      .citem {
        background-image: url("#{$baseImgUrl}/img/couponBg.png");
        background-repeat: no-repeat;
        background-size: cover;
        height: 202px;
        margin-top: 30px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .pricebox {
          width: 254px;
          flex-shrink: 0;
          text-align: center;
          color: #fff;
          padding: 0 24px;
          font-size: 0;

          .priceUnit {
            font-size: 36px;
          }

          .price {
            font-size: 48px;
          }

          .priceDes {
            font-size: 24px;
            padding: 25px 0 0 0;
            line-height: 30px;
          }
        }

        .iteminfo {
          flex: 1;
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding: 30px 32px;

          .itemname {
            color: $fzColor;
            font-size: 32px;
          }

          .date {
            font-size: 26px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .icon {
              color: #dfdfdf;

              &.active {
                color: $calendarWeekColor;
              }
            }
          }

          .nowdate {
            font-size: 24px;
            color: #646464;
          }
        }
      }
    }

    .nouser {
      position: absolute;
      bottom: 0;
      left: 0;
      z-index: 999;
      box-sizing: border-box;
      width: 100%;
      padding: 5px 16px;
      font-weight: 500;
      background-color: #fff;
    }
  }
  .remarks {
    flex-direction: column;
    &_label {
      margin-bottom: 10px;
      span {
        opacity: 0.5;
        padding-left: 6px;
      }
    }

    /deep/ .van-field__control {
      background-color: #f9f9f9;
      padding: 20px;
      box-sizing: border-box;
    }
  }
}
</style>
